package com.ycy;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * 演示重入锁
 */
@Slf4j
public class LockDemo {

  private final RedissonClient redissonClient;

  public LockDemo(RedissonClient redissonClient) {
    this.redissonClient = redissonClient;
  }

  public static void main(String[] args)   {
    Config config = new Config();
    config.useSingleServer().setAddress("redis://127.0.0.1:6379");
    LockDemo lockDemo = new LockDemo(Redisson.create(config));

    lockDemo.reentrantLock(2);
    lockDemo.release();
  }

  public void release() {
    this.redissonClient.shutdown();
  }

  /**
   * 127.0.0.1:8000> HGETALL reentrant-lock
   * 1) "d8769b01-5cfc-4221-aab5-5b5a1d30958f:44"
   * 2) "2"
   *
   * @param i
   */
  public void reentrantLock(int i) {
    if (i <= 0) return;
    RLock reentrantLock = redissonClient.getLock("reentrant-lock");

    reentrantLock.lock();
    try {
      try {
        // do something
        System.out.println("do work");
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      reentrantLock(i - 1);
    } finally {
      reentrantLock.unlock();
    }

    this.release();
  }

}
